from odoo import fields, models, api
from odoo.exceptions import UserError, ValidationError

from ...functions.operation_control_fc import OperationControlFC
from .rp_courier_mail_route import EXPRESS_CATEGORY


class RPShipperMailRoute(models.Model):
    _name = "rp.shipper.mail.route"
    _description = '托运商邮路'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _sql_constraints = [('unique_name', 'UNIQUE(name,shipper_id)', '同一个托运商，邮路名称必须唯一'),
                        ('unique_code', 'UNIQUE(code,shipper_id)', '同一个托运商，邮路编码必须唯一')]

    shipper_id = fields.Many2one(string='托运商', comodel_name='rp.shipper', ondelete='cascade')
    courier_id = fields.Many2one(string='承运商', comodel_name='rp.courier', related='shipper_id.courier_id', store=True, tracking=True)
    available_courier_mail_route_ids = fields.Many2many(string='可用邮路', comodel_name='rp.courier.mail.route', compute='_compute_available_courier_mail_route_ids')
    courier_mail_route_id = fields.Many2one(string='承运商邮路', comodel_name='rp.courier.mail.route', tracking=True)

    name = fields.Char(string='名称', required=True, copy=False, index=True, tracking=True)
    code = fields.Char(string='编码', readonly=True, copy=False, index=True)

    package_type_ids = fields.Many2many(string='包裹类型', comodel_name='rp.package.type', required=True, relation='rp_shipper_mail_route_and_package_type_rel', column1='shipper_mail_route_id', column2='package_type_id', tracking=True)

    aging_available_ids = fields.Many2many(string='可用时效', comodel_name='rp.aging', related='courier_mail_route_id.aging_ids')
    aging_ids = fields.Many2many(string='时效', comodel_name='rp.aging', required=True, relation='rp_shipper_mail_route_and_aging_rel', column1='shipper_mail_route_id', column2='aging_id', tracking=True)

    ship_from_country_group_available_ids = fields.Many2many(string='可用启运地', comodel_name='res.country.group', related='courier_mail_route_id.ship_from_country_group_ids')
    ship_from_country_group_ids = fields.Many2many(string='启运地', comodel_name='res.country.group', required=True,
                                                   relation="rp_shipper_route_from_country_group_rel", column1='shipper_mail_route_id', column2='country_group_id', tracking=True)

    ship_to_country_group_available_ids = fields.Many2many(string='可用目的地', comodel_name='res.country.group', related='courier_mail_route_id.ship_to_country_group_ids')
    ship_to_country_group_ids = fields.Many2many(string='目的地', comodel_name='res.country.group', required=True,
                                                 relation='rp_shipper_route_to_country_group_rel', column1='shipper_mail_route_id', column2='country_group_id', tracking=True)

    same_city_flag = fields.Boolean(string='同城', related='courier_mail_route_id.same_city_flag', readonly=True, store=True)
    same_province_flag = fields.Boolean(string='同省', related='courier_mail_route_id.same_province_flag', readonly=True, store=True)
    express_category = fields.Selection(string='发件类型', selection=EXPRESS_CATEGORY, related='courier_mail_route_id.express_category', readonly=True, store=True)

    # 头尾程
    operation_display = fields.Char(string='头尾程', default='-,-,-,-', compute='_depends_fulfill_operation', store=True, tracking=True)
    operation_dropoff = fields.Boolean(string='网点收件', default=True)
    operation_pickup = fields.Boolean(string='上门取件', default=True)
    operation_collect = fields.Boolean(string='网点取件', default=True)
    operation_delivery = fields.Boolean(string='送货上门', default=True)

    available_value_added_ids = fields.Many2many(string='可用增值服务', comodel_name='rp.value.added.service', related='courier_mail_route_id.value_added_ids')
    value_added_ids = fields.Many2many(string='增值服务', comodel_name='rp.value.added.service',
                                       relation='rp_shipper_mail_and_value_added_rel', column1='shipper_mail_id', column2='value_added_id')

    active_flag = fields.Boolean(string='有效', default=True, related='courier_mail_route_id.active_flag', tracking=True)

    @api.depends('courier_id')
    def _compute_available_courier_mail_route_ids(self):
        for record in self:
            if record.courier_id:
                record.available_courier_mail_route_ids = record.courier_id.courier_mail_route_ids
            else:
                record.available_courier_mail_route_ids = self.env['rp.courier.mail.route'].browse()

    @api.onchange('courier_mail_route_id')
    def _onchange_fulfill_courier_mail_route_info(self):
        if self.courier_mail_route_id:
            self.update({'code': "'" + self.courier_mail_route_id.code,
                         'operation_display': True if self.courier_mail_route_id.operation_pickup else False,
                         'operation_pickup': True if self.courier_mail_route_id.operation_pickup else False,
                         'operation_dropoff': True if self.courier_mail_route_id.operation_dropoff else False,
                         'operation_delivery': True if self.courier_mail_route_id.operation_delivery else False,
                         'package_type_ids': [(6, 0, self.courier_mail_route_id.package_type_ids.ids)],
                         'aging_ids': [(6, 0, self.courier_mail_route_id.aging_ids.ids)],
                         'value_added_ids': [(6, 0, self.courier_mail_route_id.value_added_ids.ids)],
                         'ship_from_country_group_ids': [(6, 0, self.courier_mail_route_id.ship_from_country_group_ids.ids)],
                         'ship_to_country_group_ids': [(6, 0, self.courier_mail_route_id.ship_to_country_group_ids.ids)]})

    @api.depends('operation_pickup', 'operation_dropoff', 'operation_delivery', 'operation_collect')
    def _depends_fulfill_operation(self):
        for s in self:
            operation = OperationControlFC(self.env, s.operation_dropoff, s.operation_pickup, s.operation_collect, s.operation_delivery)

            s.write({'operation_display': operation.fulfill_display(),
                     'value_added_ids': [(6, 0, operation.update_value_add_list(s.value_added_ids.ids))]})

    @api.constrains('operation_pickup', 'operation_dropoff', 'operation_delivery', 'operation_collect')
    def _check_operation_info(self):
        for s in self:
            if s.shipper_id:
                if all([s.shipper_id.operation_pickup is False, s.operation_pickup is True]):
                    raise ValidationError('当前托运商不支持上门取件')
                if all([s.shipper_id.operation_dropoff is False, s.operation_dropoff is True]):
                    raise ValidationError('当前托运商不支持网点收件')
                if all([s.shipper_id.operation_delivery is False, s.operation_delivery is True]):
                    raise ValidationError('当前托运商不支持送货上门')
                if all([s.shipper_id.operation_collect is False, s.operation_collect is True]):
                    raise ValidationError('当前托运商不支持网点取件')

    @api.onchange('value_added_ids')
    def _onchange_value_added_ids(self):
        """ 头尾程的增值服务不允许删除 """
        if self.value_added_ids:
            operation = OperationControlFC(self.env, self.operation_dropoff, self.operation_pickup, self.operation_collect, self.operation_delivery)
            if not operation.monitor_value_add_list(self.value_added_ids.ids):
                raise UserError('增值服务中的头尾程不允许删除')

    def name_get(self):
        res = []
        for s in self:
            name = s._get_name()
            res.append((s.id, name))
        return res

    def _get_name(self):
        """ 重写display_name """
        name = self.name
        if self._context.get('show_display'):
            display_name = self.name if self.name else ''
            code = self.code if self.code else ''

            name = code + ' - ' + display_name

        return name
